import Vue from 'vue';
import jude from "./Tools/Jude";
import device from "./device";
import Login from "./Login";
import dateFormat from './date/format';
import getMonthDay from './date/getMonthDay';
import dateRange from './date/range';
import dayDiff from './date/dayDiff';
import transformDate from './date/transformDate';
import timeForMat from './date/timeForMat';
import {Storage} from './Storage/index.js';
import Authorize from './authorize/index';
import {
    $$$setTimeout,
    absUrl,
    addGlobalModal,
    addToUrlQuery,
    ApJSBridge,
    deepClone1,
    failToast,
    getBasicUserInfoSync,
    getCurrentPage,
    getCurrentPageSync,
    getLastPageSync,
    getNumber,
    isLoginExpired,
    login,
    mapKeys,
    mapKeysData,
    number_format,
    object2style,
    openSecondInterval,
    qs,
    randomColor,
    randomImage,
    randomNum,
    showGlobalModal,
    showLoading,
    showToast,
    signOut,
    strLength,
    style2object,
    textToast,
    openShareModalSync,
    openAlertModalSync,
    arrShuffle,
    showModalSync,
    unique,
    colorRGBtoHex,
    hexToRgba,
    trim
} from "./util";

import wx_jssdk from './Wechat'
import {debounce} from "./lodash/throttle";
import validate from "./Tools/validate";
import $upload from '@/common/upload/index.js'

const {host, TAB_LINK, VERIFY_LINK, NEED_AFRESH_LOGIN, ERROR_STATUS, TAG_IMAGES, PATH_TYPE, ICON_PATH, NEED_AFRESH_REFRESH, SOURCE_LIST} = require('./config/index');

Vue.NEED_AFRESH_REFRESH = NEED_AFRESH_REFRESH;
Vue.NEED_AFRESH_LOGIN = NEED_AFRESH_LOGIN;
Vue.PATH_TYPE = PATH_TYPE;
Vue.VERIFY_LINK = VERIFY_LINK;
Vue.ERROR_STATUS = ERROR_STATUS;
Vue.TAG_IMAGES = TAG_IMAGES;
Vue.SOURCE_LIST = SOURCE_LIST;

Vue.prototype.NEED_AFRESH_REFRESH = NEED_AFRESH_REFRESH;
Vue.prototype.NEED_AFRESH_LOGIN = NEED_AFRESH_LOGIN;
Vue.prototype.PATH_TYPE = PATH_TYPE;
Vue.prototype.VERIFY_LINK = VERIFY_LINK;
Vue.prototype.ERROR_STATUS = ERROR_STATUS;
Vue.prototype.TAG_IMAGES = TAG_IMAGES;
Vue.prototype.SOURCE_LIST = SOURCE_LIST;

const $toast = {
    show: showToast,
    text: textToast,
    fail: failToast
};
const $loading = {
    show: showLoading,
    hide: () => uni.hideLoading()
};

const $util = {
    isLoginExpired,
    mapKeys,
    mapKeysData,
    qs,
    jude,
    strLength,
    getCurrentPage,
    getCurrentPageSync,
    getLastPageSync,
    dateFormat,
    getMonthDay,
    dateRange,
    dayDiff,
    timeForMat,
    transformDate,
    Login,
    ApJSBridge,
    style2object,
    object2style,
    absUrl,
    getNumber,
    randomNum,
    randomColor,
    randomImage,
    login,
    openSecondInterval,
    $$$setTimeout,
    addToUrlQuery,
    deepClone1,
    addGlobalModal,
    showGlobalModal,
    openShareModalSync,
    openAlertModalSync,
    arrShuffle,
    showModalSync,
    number_format,
    unique,
    colorRGBtoHex,
    hexToRgba,
    trim
};

Vue.$toast = $toast;
Vue.prototype.$toast = $toast;
Vue.$loading = $loading;
Vue.prototype.$loading = $loading;
Vue.$upload = $upload;
Vue.prototype.$upload = $upload;
Vue.$global_util = $util;
Vue.prototype.$util = $util;
/**
 * 退出登录
 */
Vue.signOut = signOut;
Vue.prototype.signOut = signOut;

Vue.getBasicUserInfoSync = getBasicUserInfoSync;
Vue.prototype.getBasicUserInfoSync = getBasicUserInfoSync;

Vue.$device = device;
Vue.prototype.$device = device;
Vue.$Storage = Storage;
Vue.prototype.$Storage = Storage;

Vue.$wx_jssdk = wx_jssdk;
Vue.prototype.$wx_jssdk = wx_jssdk;

const authorize = new Authorize(wx_jssdk);
Vue.$auth = authorize;
Vue.prototype.$auth = authorize;

/*****************************过滤器***************************************/
Vue.filter('ic_image_filter', input => {
    return absUrl(input)
});
Vue.filter('ic_icon_filter', (input, key) => {
    if (/^https?:\/\/(([a-zA-Z0-9_-])+(\.)?)*(:\d+)?(\/((\.)?(\?)?=?&?[a-zA-Z0-9_-](\?)?)*)*$/i.test(input)) return input;
    if (TAG_IMAGES["error"] === input || TAG_IMAGES["avatar_error"] === input) return input;
    return typeof key === "string" && TAG_IMAGES[key] ? TAG_IMAGES[key] : ' ';
});
Vue.filter('ic_date_format_filter', (input, fmt, bol = false) => {
    if (!bol) return dateFormat(input, fmt);
    return dateFormat(input ? input : Date.now(), fmt)
})
Vue.filter('ic_money_filter', (input, decimals, unit) => {
    if (!jude.isNumberOfNaN(decimals) || unit) {
        unit = decimals || unit || ''
    }
    if (unit) {
        unit += ''
    }
    let num = null;
    if (jude.isNumberOfNaN(decimals)) {
        num = number_format(input)
    } else {
        num = parseFloat(number_format(input))
    }
    return unit ? `${unit} ${num}` : num;
});
Vue.filter('ic_number_filter', (input) => {
    return parseFloat(number_format(input))
})
/**
 * 手机***处理
 */
Vue.filter('ic_mobile_filter', (input) => {
    if (null !== input && input !== undefined) {
        const pat = /(\d{3})\d*(\d{4})/;
        return (input + '').replace(pat, '$1****$2');
    } else {
        return "";
    }
})

const LETTER = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "X", "Y", "Z"]

Vue.filter('ic_letter_filter', (input) => {
    if (!jude.isNumberOfNaN(input)) return input;
    return LETTER[input]
});

import {mapGetters} from 'vuex'

Vue.mixin({
    onShow() {
        this.isGlobalFabs = false;
    },
    data() {
        const vm = this;
        const systemInfo = this.SystemInfo || {};
        const object2style = $util.object2style;
        const statusHeight = $util.getNumber(systemInfo.StatusBar, 0);
        const height = $util.getNumber(systemInfo.bottomSysBarHeight, 0);
        const BottomSysBarStyle = this.$util.object2style({height: `${systemInfo.bottomSysBarHeight}px`})
        const BottomSysBarPadStyle = this.$util.object2style({paddingBottom: `${systemInfo.bottomSysBarHeight}px`})
        // console.log(vm.px2upx(statusHeight + 45), "+++++++++++++++++++++++++++++++++++++" + statusHeight);
        return {
            BottomSysBarStyle: BottomSysBarStyle,
            BottomSysBarPadStyle: BottomSysBarPadStyle,
            BottomSysBarGlobalHeight: height,
            StatusBarGlobalHeight: statusHeight,
            StatusBarGlobalStyle: object2style({height: statusHeight + 'px'}),
            GlobalFabs: {
                x: 300,
                y: 10,
                x1: 0,
                y1: 0,
            },
            isGlobalFabs: false,
            navBarTop: vm.px2upx(statusHeight + 45),
            navBarBottom: 0,
            globalSmsCodeLen: 6,//全局短信验证码长度配置
            navigationBarOptions: {},// 自定义导航options
            icon__: " ",
            pageHeight: systemInfo.windowHeight || '100%',
        }
    },
    onShareAppMessage(res) {
        const forward_image_path = TAG_IMAGES.forward_image_path
        if (res.from === 'button') {// 来自页面内分享按钮
            console.log(res, "++++++++onShareAppMessage+++++++++++++")
        }
        console.log(res, "准备++++++++onShareAppMessage+++++++++++++", this.$$$getShareAppMessage);
        if (typeof this.$$$getShareAppMessage === "function") {
            const share = this.$$$getShareAppMessage();
            console.log(share, "进入分享++++++++onShareAppMessage+++++++++++++");
            if (!share.imageUrl) share.imageUrl = forward_image_path;
            return share
        } else {
            return {
                title: "给你推荐一个高效的客户管理工具",
                path: "pages/home/index",
                imageUrl: forward_image_path
            };
        }
    },
    computed: {
        ...mapGetters({
            $$$SystemInfo: 'System/systemInfo'
        }),
        ...mapGetters({
            noDataType: 'System/noDataType', //1：登录 2：公司 3：名片
        }),
        // 设置mescroll-body的高
        mescrollHeight() {
            const windowHeight = this.$$$SystemInfo.windowHeight;
            const navBarTop = this.navBarTop;
            const navBarBottom = this.navBarBottom;
            // console.log(windowHeight * 2 - navBarTop - navBarBottom, navBarTop, navBarBottom, 'mescrollHeight');
            return windowHeight * 2 - navBarTop - navBarBottom;
        }
    },
    methods: {
        // 跳转个人版名片(查看)
        handleViewCardPersonal(card_id) {
            if (card_id === 0) return;
            // /pages/mycard/personage/personage?id=${this.responeData.customer_card_id}&othersCode=&type=1
            if (!jude.isEmpty(card_id) && (typeof card_id === "number" || typeof card_id === "string")) {
                const path = '/pages/mycard/personage/personage?' + qs.stringify({
                    id: card_id,
                    othersCode: "",
                    type: 1
                });
                console.log(path, '跳转个人版名片');
                this.handleCreateCardPersonal(path)
            }
        },
        // 跳转个人版名片（创建）
        handleCreateCardPersonal(path = "pages/mycard/create/create") {
            // develop 开发版
            // trial 体验版
            // release 正式版
            const appId = this.$config.card_personal_appId;
            const envVersion = this.$config.envVersion;
            const vm = this;
            const data = {
                appId,
                path: path,
                envVersion: envVersion,
                success() {
                    vm.$store && vm.$store.commit('System/setOtherReturnRefresh', true);
                },
                complete() {
                    console.log(arguments, 'card_personal');
                }
            }
            console.log(data, '跳转个人版名片');
            uni.navigateToMiniProgram && uni.navigateToMiniProgram(data)
        },
        /**
         * 获取个人用户信息
         *
         * @returns {Promise<unknown>}
         */
        $$$getUserInfo() {
            const vm = this;
            return new Promise(async (resolve, reject) => {
                const userInfo = vm.$util.Login.userInfo;
                if (!userInfo.user_id) {
                    const result = await vm.getBasicUserInfoSync();
                    if (result.code === 0) {
                        resolve(result.data)
                    } else {
                        vm.$toast.text(result.message || "获取用户信息失败")
                        reject()
                    }
                } else {
                    resolve(userInfo)
                }
            })
        },
        /**
         * 邀请加入团队与部门
         *
         * @param invite_code {string|number} 邀请码 为空空会自动请求新的
         * @param imageUrl {string|url} 转发&分享分享图
         * @param path {string} 转发&分享路径
         * @param scene {object} 转发&分享携带参数
         * @param type 调用类型 为空：使用全局分享弹窗 ；get：获取分享参数
         * @returns {Promise<{result, userInfo: null}|void>}
         */
        async handleInviteMember({invite_code, imageUrl, path = "pages/settled/member/scancode", scene = {}}, type) {
            const vm = this;
            this.$loading.show("获取中")
            let curPage = await this.$util.getCurrentPageSync();
            if (curPage.$vm) curPage = curPage.$vm;
            const query = {scene}
            if (typeof invite_code !== "string" || typeof invite_code !== "number" || jude.isEmpty(invite_code)) {
                const result = await this.$ajax.Temp.getInviteCode({...scene, page: path})
                if (type === 'get') {
                    let userInfo = null;
                    if (result.code === 0) userInfo = await this.$$$getUserInfo();
                    this.$loading.hide();
                    return Promise.resolve({result, userInfo});
                } else if (result.code === 0 && result.data && result.data.invite_code) {
                    invite_code = result.data.invite_code;
                    query.invite_data = result.data;
                    curPage.$$$PageShareData = result.data;
                } else {
                    this.$loading.hide();
                    return this.$toast.text(result.message || "获取邀请码失败");
                }
            }
            const share_query = this.$util.qs.stringify({invite_code})
            let userInfo = await this.$$$getUserInfo()
            if (!imageUrl) imageUrl = TAG_IMAGES.share_join_path
            curPage.$$$getShareAppMessage = function () {
                return {
                    title: `${userInfo.company_name}的${userInfo.nickname}邀请你加入TA的团队`,
                    path: `/${path}?${share_query}`,
                    imageUrl,
                    query,
                    success() {
                        vm.$toast.show("分享成功")
                    },
                    fail() {
                        vm.$toast.show("分享失败")
                    }
                }
            }
            this.$loading.hide();
            const isInternal = !!(scene && scene.department_id);
            let title = isInternal && scene.department_name ? `通过以下方式添加到${scene.department_name}` : "";
            const result = await vm.$util.openShareModalSync({isInternal, title});
            this.$nextTick(function () {
                if (result && result.index === 1) {
                    this.handleToLoginLink({
                        path: "/pages/share/index",
                        query: {invite_code, department_id: scene || scene.department_id}
                    })
                } else if (result && result.index === 2) {
                    this.handleToLoginLink({
                        path: "/pages/organized/operate/select-member",
                        query: {invite_code, department_id: scene && scene.department_id}
                    })
                }
            })
        },
        px2upx(num) {
            const winWidth = uni.getSystemInfoSync().windowWidth;
            return (Number(num) * (750 / winWidth))
        },
        $$$setNavigationBarTitle({title, isBack, backText, backTextColor, frontColor, backgroundColor} = {}) {
            let that = this;
            let page = that.$util.getCurrentPage();

            const navigationBarOptions = this.navigationBarOptions;
            let ColorData = {};
            frontColor = jude.colorFilter(frontColor);
            backgroundColor = jude.colorFilter(backgroundColor);
            switch (true) {
                case !!frontColor:
                    this.navigationBarOptions.frontColor = frontColor;
                    ColorData.frontColor = frontColor;
                case !!backgroundColor:
                    this.navigationBarOptions.backgroundColor = backgroundColor;
                    ColorData.backgroundColor = backgroundColor;
                case jude.isColor(backTextColor):
                    this.navigationBarOptions.backTextColor = backTextColor;
                case jude.isBoolean(isBack):
                    this.navigationBarOptions.isBack = isBack;
                case jude.isString(backText):
                    this.navigationBarOptions.backText = backText;
                default:
                    this.navigationBarOptions.title = jude.isString(title) ? title : navigationBarOptions.title;
            }
            let arr = [];
            const p1 = new Promise(function (resolve, reject) {
                uni.setNavigationBarTitle({
                    title: that.navigationBarOptions.title,
                    complete(res) {
                        resolve(res)
                    }
                });
                //#ifdef H5
                if (navigationBarOptions.hideNavigation === true || that.HideNavigation === true) {
                    if (!page || page.route === that.route) {
                        window.document.title = that.navigationBarOptions.title || ''
                    }
                }
                //#endif
            });
            arr.push(p1);
            if (ColorData.frontColor && !/^#(ffffff|000000)$/i.test(ColorData.frontColor)) {
                delete ColorData.frontColor
            }
            if (ColorData.frontColor && ColorData.backgroundColor) {
                const p2 = new Promise(function (resolve, reject) {
                    uni.setNavigationBarColor({
                        ...ColorData,
                        complete(res) {
                            resolve(res)
                        }
                    })
                });
                arr.push(p2);
            }
            return Promise.all(arr);
        },
        $$$getQuery(key, defaultVal, type) {
            const that = this;
            const {isEmpty} = that.$util.jude;
            if (typeof key === 'string') {
                let val = '';
                if (!!that.__options && !!that.__options.query) {
                    val = that.__options.query[key]
                }
                if (isEmpty(val) && !!that.$Route && !!that.$Route.query) {
                    val = that.$Route.query[key]
                }
                const value = isEmpty(val) ? (isEmpty(defaultVal) ? '' : defaultVal) : val;
                if (type === 'number') {
                    return that.$util.getNumber(value, defaultVal)
                }
                return value;
            }
            return isEmpty(defaultVal) ? '' : defaultVal;
        },
        $$$validate(model, rules) {
            let result = validate(model, rules);
            let message;
            if (result) {
                for (const k in result) {
                    const val = result[k];
                    for (const v of val) {
                        if (v) {
                            const reg = new RegExp(`^(${k.replace(/\_/g, ' ')})`, 'i');
                            message = v.replace(reg, '').trim();
                            break;
                        }
                    }
                    break;
                }
            }
            return result ? {result, message} : result;
        },

        // 监听导航栏实际高度
        handleNavBarLoad(data) {
            if (data && jude.isNumberOfNaN(data.height)) {
                this.navBarTop = this.px2upx(data.height);
            }
        },
        // 监听下导航栏实际高度
        handleFooterBarLoad(data) {
            if (data && jude.isNumberOfNaN(data.height)) {
                this.navBarBottom = this.px2upx(data.height);
            }
        },
        /**
         * 图片404替换缺省图
         *
         * @param obj {object} 图片存在的对象 传null 指定this
         * @param key {String} 图片在obj中的那个key中
         * @param type {String} 默认空  avatar：替换头像缺省图
         */
        handleImageError(obj, key, type) {
            if (typeof key !== "string") return;
            console.log(key, '加载失败图片');
            let img;
            switch (type) {
                case 'company':
                    img = TAG_IMAGES.company_error;
                    break;
                case 'avatar':
                    img = TAG_IMAGES.avatar_error;
                    break;
                default:
                    img = TAG_IMAGES.error;
            }
            if (typeof obj === 'function') return obj({[key]: img});
            if (!jude.isEmptyObject(obj, true) && obj[key] !== img) {
                obj[key] = img
            } else if (this[key] !== img) {
                this[key] = img
            }
        },
        /**
         * 路由跳转
         *
         * @desc 该方法会检测是否存在token
         * @param url {string|object} 传字符串 填充 url.path
         * @param url.path {string} 跳转页面
         * @param url.query {object} 跳转携带参数
         * @param bol {boolean} 默认检测是否需要登录
         */
        handleToLoginLink(url, bol = true) {
            const vm = this;
            if (vm.noDataType === 2 && bol === 2) {
                return uni.showModal({
                    content: ERROR_STATUS[6001],
                    confirmText: "立即前往",
                    success({confirm, cancel}) {
                        if (confirm === true) {
                            vm.$$router.push("/pages/settled/index")
                        }
                    }
                })
            }
            let query, option = url;
            if (!this.$util.jude.isEmptyObject(option)) {
                url = option.path;
                query = option.query;
            }
            if (typeof url !== "string" || this.$util.jude.isEmpty(url)) return;
            let isLogin = false;
            if (typeof this.isLogin === 'boolean') {
                isLogin = this.isLogin
            } else {
                let userInfo = this.$util.Login.userInfo;
                console.log(userInfo, '++++++++++++++++++++++++userInfo++++++++++++++++++++');
                isLogin = !!this.$util.Login.token && !!userInfo.userId;
            }
            if (bol && !isLogin && false) {
                if (query) url = this.$util.addToUrlQuery(url, query);
                uni.showModal({
                    title: '登录提示',
                    content: '未登录或登录已过期，请重新登录',
                    showCancel: false,
                    complete() {
                        vm.$Storage.setStorageSync('redirectUrl', url, '1d');
                        vm.$$router.push({
                            url: vm.$config.LOGIN_PATH,
                            isToMiniProgram: true
                        });
                    }
                })
            } else {
                vm.$$router.push(option)
            }
        },
        /**
         * 空操作
         */
        noop() {

        },
        /**
         * 兼容原生小程序
         *
         * @param obj
         */
        setData: function (obj) {
            let that = this;
            let keys = [];
            let val, data;
            Object.keys(obj).forEach(key => {
                keys = key.split('.')
                val = obj[key];
                data = that.$data;
                keys.forEach(function (key2, index) {
                    if (index + 1 == keys.length) {
                        that.$set(data, key2, val)
                    } else {
                        if (!data[key2]) {
                            that.$set(data, key2, {})
                        }
                    }
                    data = data[key2]
                })
            })
        },
        /**
         * 拨打电话
         * @param num
         */
        makePhoneCall(num) {
            num && uni.makePhoneCall({
                phoneNumber: num,
                complete() {
                    console.log(...arguments);
                }
            })
        },
        /**
         * 复制
         * @param text
         */
        handleClipboardData(text) {
            const vm = this;
            const {isEmpty} = this.$util.jude;
            if (!isEmpty(text) && (typeof text === 'string' || typeof text === "number"))
                uni.setClipboardData({
                    data: text,
                    success() {
                        vm.$toast.show('复制成功')
                    },
                    complete() {
                        console.log(...arguments);
                    }
                })
            else {
                return vm.$toast.fail('复制失败');
            }
        },
        /**
         * 部门与成员选择操作
         *
         * @param item 选项参数
         * @param index 选项索引
         * @param value
         * @param branchList
         * @param dataList
         * @returns {Promise<void>}
         */
        async handleOperateTapPopup({item, index, value}, branchList, dataList) {
            const vm = this
            const userInfo = this.userInfo
            console.log(item, index, value, "部门与成员选择操作");
            if (value.type === 1) {// 部门操作
                switch (item.id) {
                    case 1:// 编辑部门
                        vm.handleToLoginLink({
                            path: "/pages/organized/operate/branch-form",
                            query: {branch_id: value.id, parent_id: value.parent_id}
                        })
                        break;
                    case 5:// 删除部门
                        const result = await Vue.$global_util.openAlertModalSync({
                            title: "是否删除该部门？",
                            content: "删除部门后，该部门成员也将该部门解散"
                        })
                        if (result.confirm) {
                            const result = await Vue.$ajax.Organized.deleteBranch({id: value.id})
                            if (result.code === 0) {
                                const fIndex = branchList.findIndex(v => value.id === v.id);
                                if (fIndex > -1) branchList.splice(fIndex, 1);
                                vm.$toast.show("删除成功")
                            } else {
                                vm.$toast.text(result.message)
                            }
                        }
                        break;
                    case 0:
                        this.handleToLoginLink({
                            path: "/pages/organized/index",
                            query: {
                                branch_type: value.level + 1,// 下一个部门的层级
                                id: value.id
                            }
                        })
                        break;
                    default:
                }
            } else { // 成员操作
                switch (item.id) {
                    case 1:// 编辑成员
                        vm.handleToLoginLink({
                            path: "/pages/organized/operate/edit-form",
                            query: {id: value.user_id}
                        })
                        break;
                    case 7:// 设置管理员权限
                        const result = await this.$util.openAlertModalSync({
                            title: "将其设置为管理员？",
                            isHtml: true,
                            content: `<p style="font-size:28rpx;color: #6B6B6B;padding-left: 60rpx;line-height:48rpx;">管理员权限： <br/>· 允许查看本部门数据 <br/>· 允许管理本部门成员 <br/>· 允许管理部门</p>`
                        })
                        if (result && result.confirm) {
                            const result = await this.$ajax.Organized.setStaffRole({user_id: value.user_id, role: 1})
                            if (result.code === 0) {
                                const fIndex = dataList.findIndex(v => value.user_id === v.user_id);
                                dataList[fIndex].role = 1;
                            } else {
                                this.$toast.text(result.message);
                            }
                        }
                        break;
                    case 8:// 取消管理员权限
                        const result1 = await this.$util.openAlertModalSync({
                            title: "取消其管理员身份？",
                            content: `取消其管理员身份，该成员将回归普通身份。`
                        })
                        if (result1 && result1.confirm) {
                            const result = await this.$ajax.Organized
                                .setStaffRole({user_id: value.user_id, role: 2})
                            if (result.code === 0) {
                                const fIndex = dataList.findIndex(v => value.user_id === v.user_id);
                                dataList[fIndex].role = 2;
                            } else {
                                this.$toast.text(result.message);
                            }
                        }
                        break;
                    case 3:// 移除部门&公司
                        let tapIndex
                        if (value.branch_id) {
                            tapIndex = await (new Promise((resolve, reject) => {
                                uni.showActionSheet({
                                    itemList: ["从当前部门移除", "从当前公司移除"],
                                    success({tapIndex}) {
                                        resolve(tapIndex)
                                    },
                                    fail: reject
                                })
                            }))
                        }
                        if (!value.branch_id || tapIndex === 1) {
                            const result = await this.$util.openAlertModalSync({
                                title: "确定移除该成员？",
                                content: `移除后该成员的数据将删除。`,
                                contentAlign: "center"
                            })
                            if (result && result.cancel) return;
                        }
                        vm.$loading.show('移除中。。。')
                        let flag = !value.branch_id || tapIndex === 1
                        const result2 = await vm.$ajax.Organized.removeStaff({
                            dist_user_id: value.user_id,
                            department_id: flag ? 0 : value.branch_id
                        })
                        vm.$loading.hide()
                        if (result2.code === 0) {
                            const fIndex = dataList.findIndex(v => value.user_id === v.user_id);
                            if (fIndex > -1) dataList.splice(fIndex, 1);
                            if (flag && userInfo.user_id === value.user_id) {
                                await vm.$util.showModalSync({
                                    title: "温馨提示",
                                    content: "你已被移除该企业，请重新登录",
                                    showCancel: false
                                })
                                Login.toLogin();
                            } else {
                                vm.$toast.show("移除成功")
                            }
                            // flag &&
                        } else if (result2.code === 6002) {
                            const result = await vm.$util.openAlertModalSync({
                                content: `该成员下存在客户，请先移交后再移除。`,
                                confirmText: "前往移交"
                            })
                            if (result && result.confirm) {
                                this.handleToLoginLink({
                                    path: "/pages/organized/client/transfer",
                                    query: {
                                        id: value.user_id,
                                        name: value.nickname
                                    }
                                })
                            }
                        } else {
                            this.$toast.text(result2.message || '移除出错')
                        }
                        break;
                    case 2:// 移交客户
                        this.handleToLoginLink({
                            path: "/pages/organized/client/transfer",
                            query: {
                                id: value.user_id,
                                name: value.nickname
                            }
                        })
                        break
                    case 6:
                        this.handleToLoginLink({
                            path: "/pages/organized/operate/transfer",
                            query: {
                                id: value.user_id,
                                name: value.nickname
                            }
                        })
                        break
                    case 0:
                        this.handleToLoginLink({
                            path: "/pages/organized/staff/details",
                            query: {
                                id: value.user_id
                            }
                        })
                        break;
                    default:
                }
            }
        },
        /**
         * 打开地图 获取定位
         * @returns {Promise<unknown>}
         */
        $chooseLocation() {
            let that = this;
            return new Promise((resolve, reject) => {
                uni.chooseLocation({
                    success(res) {
                        resolve(res);
                    },
                    async fail(e) {
                        if (that.$auth.authSetting['scope.userLocation']) return;
                        let res = await that.$auth.openSetting("scope.userLocation");
                        if (res.status) {
                            uni.chooseLocation({
                                success(res) {
                                    resolve(res);
                                },
                            });
                        } else {
                            reject(e);
                        }
                    },
                });
            });
        },
        // 验证权限
        getVerifyAuth(curInfo, userInfo) {
            try {
                if (userInfo.role === 0 || userInfo.user_id === curInfo.user_id) {
                    return true;
                } else if (userInfo.role === 1 && curInfo.role !== 0) {
                    if (curInfo.department_ids) {
                        const fIndex = userInfo.department_ids.findIndex(value => {
                            return curInfo.department_ids.indexOf(value + '') > -1
                        })
                        return fIndex > -1;
                    }
                    const fIndex = curInfo.department_list.findIndex(value => {
                        return userInfo.department_ids.indexOf(value.id + '') > -1
                    })
                    return fIndex > -1;
                } else {
                    return false;
                }
            } catch (e) {
                return false
            }
        }
    }
});

export {};
